package com.situ.vivamarket.api.front;

import com.situ.vivamarket.model.*;
import com.situ.vivamarket.model.front.CartItem;
import com.situ.vivamarket.model.front.Coupon;
import com.situ.vivamarket.model.front.WishlistItem;
import com.situ.vivamarket.service.front.CartItemService;
import com.situ.vivamarket.service.OrderService;
import com.situ.vivamarket.service.front.CouponService;
import com.situ.vivamarket.service.front.WishlistService;
import com.situ.vivamarket.util.JsonResult;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;
import java.util.UUID;

@RestController
@RequestMapping("/front/api/v1/shop")
public class ShopApi {
    private CartItemService cartItemService;
    private OrderService orderService;
    private WishlistService wishlistService;
    private CouponService couponService;


    @Autowired
    public void setCartItemService(CartItemService cartItemService) {
        this.cartItemService = cartItemService;
    }
    @Autowired
    public void setOrderService(OrderService orderService) {
        this.orderService = orderService;
    }
    @Autowired
    public void setWishlistService(WishlistService wishlistService) {
        this.wishlistService = wishlistService;
    }
    @Autowired
    public void setCouponService(CouponService couponService) {
        this.couponService = couponService;
    }

    //    新增购物车post,将商品添加到购物车
    @PostMapping("/cart")
    public ResponseEntity<JsonResult> shopCartAdd(@Validated CartItem ci, HttpSession session) {
//        从session里取出会员编号
        Member member = (Member) session.getAttribute("current_member_login");
        ci.setMemberId(member.getId());
        boolean success = this.cartItemService.addCartItem(ci);
        if (success) {
            return ResponseEntity.ok(JsonResult.success("添加购物车项成功"));
        } else {
            return ResponseEntity.badRequest().body(JsonResult.fail("添加购物车项失败"));
        }
    }

    //    修改购物车商品数量
    @PatchMapping("/cart")
    public ResponseEntity<JsonResult> shopCartEditQty(@Validated CartItem ci, HttpSession session) {

        Member member = (Member) session.getAttribute("current_member_login");
        ci.setMemberId(member.getId());
        boolean success = this.cartItemService.updateQty(ci);
        if (success) {
            return ResponseEntity.ok(JsonResult.success("更改购物车商品数量成功"));
        } else {
            return ResponseEntity.ok(JsonResult.fail("更改购物车商品数量失败"));
        }
    }

    //    删除购物车项
    @DeleteMapping("/cart")
    public ResponseEntity<JsonResult> shopCartDelete(Integer[] ids) {
        if (ids.length == 0) {
            return ResponseEntity.noContent().build();
        } else {
            int count = cartItemService.deleteByIds(ids);
            if (count > 0) {
                return ResponseEntity.ok(JsonResult.successData(count));
            } else {
                return ResponseEntity.ok(JsonResult.fail("删除购物车项失败"));
            }
        }
    }

    /**
     * 创建订单，从购物车提交
     * @param session
     */
    @PostMapping(value = "/checkout")
    public ResponseEntity<JsonResult> checkout(Integer[] ids, HttpSession session) {
        if (ids == null || ids.length == 0) {
            return ResponseEntity.badRequest().body(JsonResult.fail("至少购买一件商品"));
        }
        //创建订单，及订单项
        Member member = (Member) session.getAttribute("current_member_login");
        //创建订单
        Order order = new Order();
        order.setMemberId(member.getId());
        Random r = new Random();
        order.setOrderNo(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + "-" + r.nextInt(1000, 10000));
        order.setState(OrderState.CREATED); //设置订单状态
        order.setCreatedTime(LocalDateTime.now());
        //进行结算操作
        boolean success = this.orderService.checkout(order, ids);//id是insert的SQL语句里keyGenerate生成的
        if (success) {
            return ResponseEntity.ok(JsonResult.successData(order.getId()));
        } else {
            return ResponseEntity.ok(JsonResult.fail("创建订单失败"));
        }
    }
//    提交订单时，对订单项进行完善，receiver,total_pay,note和pay_type
    @PatchMapping("/checkout")
    public ResponseEntity<JsonResult> placeOrder(Order order) {
        if(order==null){
            return ResponseEntity.noContent().build();
        }
        boolean success= this.orderService.patch(order);
        if (success) {
            return ResponseEntity.ok(JsonResult.successData(order.getId()));
        }else{
            return ResponseEntity.ok(JsonResult.fail("提交(修改)订单失败"));
        }
    }




    //    新增收藏post,将商品添加到收藏列表
    @PostMapping("/wishlist")
    public ResponseEntity<JsonResult> wishlistAdd(@Validated WishlistItem wi, HttpSession session) {
//        从session里取出会员编号
        Member member = (Member) session.getAttribute("current_member_login");
        wi.setMemberId(member.getId());
        WishlistItem wiFind=wishlistService.findByUnique(wi);
//        已经有了就别加了
        if (wiFind != null) {
            return ResponseEntity.ok(JsonResult.fail("该商品已存在，请勿重复收藏"));
        }
        boolean success = this.wishlistService.addItem(wi);
        if (success) {
            return ResponseEntity.ok(JsonResult.success("添加收藏成功"));
        } else {
            return ResponseEntity.ok(JsonResult.fail("添加收藏失败"));
        }
    }
    //    删除收藏
    @DeleteMapping("/wishlist")
    public ResponseEntity<JsonResult> wishlistDelete(Integer id) {
        if (id == null) {
            return ResponseEntity.noContent().build();
        } else {
            int count = wishlistService.deleteItemById(id);
            if (count > 0) {
                return ResponseEntity.ok(JsonResult.successData(count));
            } else {
                return ResponseEntity.ok(JsonResult.fail("取消收藏失败"));
            }
        }
    }
    @PostMapping("/coupon")
    public ResponseEntity<JsonResult> couponAdd(HttpSession session) {
        Member member = (Member) session.getAttribute("current_member_login");
        if (couponService.findByMemberId(member.getId())!= null) {
            return ResponseEntity.ok(JsonResult.fail("已有优惠券，请勿重复获取"));
        }else{
            Coupon coupon=new Coupon();
            coupon.setMemberId(member.getId());
            coupon.setCode(UUID.randomUUID().toString().substring(0, 8));
            coupon.setDiscount(25);
            boolean success = couponService.add(coupon);
            if (success) {
                return ResponseEntity.ok(JsonResult.successData(coupon.getCode()));
            }else{
                return ResponseEntity.ok(JsonResult.fail("获取优惠券失败"));
            }
        }
    }
    @DeleteMapping("/coupon")
    public ResponseEntity<JsonResult> couponDelete(String code,HttpSession session) {
        Member member = (Member) session.getAttribute("current_member_login");
        System.out.println(code);
        Coupon coupon=couponService.findByMemberId(member.getId());
        if (coupon != null) {
            if(coupon.getCode().equals(code)){
                int count = couponService.delete(code);
                if (count == 0) {
                    return ResponseEntity.internalServerError().build();
                }
                return  ResponseEntity.ok(JsonResult.successData(coupon.getDiscount()));
            }else{
                return ResponseEntity.ok(JsonResult.fail("优惠码错误"));
            }
        }else{
            return ResponseEntity.ok(JsonResult.fail("尚未拥有优惠券"));
        }
    }


}


